package permission

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminuserrole"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"
)

type AdminUserRoleDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminUserRoleDao(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserRoleDao {
	return &AdminUserRoleDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// AdminUserRoleCreate - 创建用户角色关联记录
func (l *AdminUserRoleDao) AdminUserRoleCreate(userId int64, roleId int64) error {
	err := l.svcCtx.Orm.AdminUserRole.Create().
		SetAdminUserRoleUserID(userId).
		SetAdminUserRoleRoleID(roleId).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// AdminUserRoleBatchCreate - 批量创建用户角色关联记录
func (l *AdminUserRoleDao) AdminUserRoleBatchCreate(userId int64, roleIds []int64, tx *ent.Tx) error {
	var bulk []*ent.AdminUserRoleCreate
	for _, roleId := range roleIds {
		create := tx.AdminUserRole.Create().
			SetAdminUserRoleUserID(userId).
			SetAdminUserRoleRoleID(roleId).
			SetCreateAt(time.Now()).
			SetUpdateAt(time.Now())
		bulk = append(bulk, create)
	}

	// 批量创建
	err := l.svcCtx.Orm.AdminUserRole.CreateBulk(bulk...).Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// AdminUserRoleDelete - 删除用户所有角色关联记录
func (l *AdminUserRoleDao) AdminUserRoleDelete(conditions []predicate.AdminUserRole) error {
	err := l.svcCtx.Orm.AdminUserRole.Update().
		Where(conditions...).
		SetIsDelete(bizadmin.Delete).
		SetDeleteAt(time.Now()).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// UserRoleConditionsAll - 根据条件查询用户角色关联记录
func (l *AdminUserRoleDao) UserRoleConditionsAll(conditions []predicate.AdminUserRole) ([]*ent.AdminUserRole, error) {
	roleIdByUser, err := l.svcCtx.Orm.AdminUserRole.Query().
		Where(conditions...).
		Where(adminuserrole.IsDeleteEQ(bizadmin.NotDelete)).
		All(l.ctx)

	if err != nil {
		return nil, err
	}
	return roleIdByUser, nil
}
